package service

import (
	"database/sql"
	"errors"
	"gf-start-kit/app/model/auth_group"
	"gf-start-kit/library/base"
	"gf-start-kit/library/guid"
	"github.com/gogf/gf/frame/g"
)

type AuthGroupService struct {
}

type AuthGroupReq struct {
	ID     int64  `json:"id" v:"required" p:"id"`
	Pid    int64  `p:"pid"        json:"pid"`    // 父组别
	Name   string `p:"name"       json:"name"`   // 角色名称
	Rules  string `p:"rules"      json:"rules"`  // 规则ID
	Status string `p:"status"     json:"status"` // 状态
}

func (s *AuthGroupService) List(form *base.Form) ([]*auth_group.Entity, error) {
	where := " 1 = 1 "
	var params []interface{}
	if !g.IsEmpty(form.Params) {
		if !g.IsEmpty(form.Params["nickname"]) {
			where += " and nickname like ? "
			params = append(params, "%"+form.Params["nickname"]+"%")
		}
	}
	return auth_group.Model.Order(form.OrderBy).FindAll(where, params)
}
func (s *AuthGroupService) Page(form *base.Form) ([]auth_group.Entity, error) {
	where := " 1 = 1 "
	var resData []auth_group.Entity
	var params []interface{}
	if !g.IsEmpty(form.Params) {
		if !g.IsEmpty(form.Params["nickname"]) {
			where += " and nickname like ? "
			params = append(params, "%"+form.Params["nickname"]+"%")
		}
	}
	num, err := auth_group.Model.As("t").FindCount(where, params)
	form.Total = num
	if err != nil {
		return resData, err
	}
	err = auth_group.Model.Where(where, params).Order(form.OrderBy).Page(form.Page, form.PageSize).M.Structs(&resData)
	if err != nil {
		return resData, err
	}
	return resData, nil
}

func (s *AuthGroupService) Remove(id int64) (interface{}, error) {
	if id <= 0 {
		return new(auth_group.Entity), errors.New("参数不合法")
	}
	return auth_group.Model.Delete(" id = ?", id)
}

func (s *AuthGroupService) Get(id int64) (*auth_group.Entity, error) {
	if id <= 0 {
		return new(auth_group.Entity), errors.New("参数不合法")
	}
	return auth_group.Model.FindOne(" id = ?", id)
}

func (s *AuthGroupService) Save(req AuthGroupReq) (sql.Result, error) {
	req.ID = guid.NewUUID()
	return auth_group.Save(req)
}
func (s *AuthGroupService) Update(req AuthGroupReq) (sql.Result, error) {
	if req.ID <= 0 {
		return nil, errors.New("ID不能为空")
	}
	return auth_group.Model.Data(req).Where(auth_group.Columns.Id, req.ID).Update()
}
